package cn.itcast.fileopeation;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private Button btn_Write;
    private Button btn_Read;
    private TextView tv_Text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_Write = (Button)findViewById(R.id.writeBtn);
        btn_Read = (Button)findViewById(R.id.readBtn);
        tv_Text = (TextView)findViewById(R.id.conText);
        btn_Write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = "data.txt";
                String content = "helloworld";
                FileOutputStream fos = null;
                try {
                    String fileDir = Environment.getDataDirectory().toString();
                    fos = openFileOutput(fileName, MODE_PRIVATE);
                    fos.write(content.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                btn_Write.setText("文件已生成");
            }
        });
        btn_Read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = "data.txt";
                String content = "";
                FileInputStream fls = null;
                try{
                    fls = openFileInput(fileName);
                    byte[] buffer = new byte[fls.available()];
                    fls.read(buffer);
                    content = new String(buffer);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(fls != null){
                        try {
                            fls.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                tv_Text.setText(content);
            }
        });
    }
}